#include <Arduino.h>
#include "HardwareSerial.h"


#include "abootloader.h"
#include "config.h"
#include "constdef.h"
#include "EEPROM.h"
HardwareSerial RS485(PB11, PB10);


Bootloader bootloader(&RS485, APP_ADDR);

uint16_t crc16(uint8_t *buffer, uint8_t size);

void setup() {

    pinMode(PIN_LED,OUTPUT);
    pinMode(PIN_RS485_EN, OUTPUT);
    digitalWrite(PIN_RS485_EN, RS485_RX);
    EEPROM.begin();
    RS485.begin(115200);
    Serial.begin(115200);
    Serial.println("bootloader start");
    Serial.print("Bootloader Version:");
    Serial.println(BOOTLOADER_VERSION);
    delay(100);
    while (RS485.available()){
        RS485.read();
    }
    if (!bootloader.check_update_flag()){
        bootloader.jump_to_app();
    }
    Serial.println("Waiting for update");
}

void loop() {
    bootloader.poll();
//    delay(1);
}

// modbus crc16
uint16_t crc16(uint8_t *buffer, uint8_t size) {
    uint16_t crc = 0xFFFF;
    for (uint8_t i = 0; i < size; i++) {
        crc ^= buffer[i];
        for (uint8_t j = 0; j < 8; j++) {
            if (crc & 0x01) {
                crc = (crc >> 1) ^ 0xA001;
            } else {
                crc = crc >> 1;
            }
        }
    }
    return crc;
}